import sqlobject

# basic configuration
DEFAULT_HOST = 'localhost'
DEFAULT_USER = 'root'
DEFAULT_PASS = ''
DEFAULT_CORE_DB  = 'sms_db'

'''
Connection class for mysql
'''
class MysqlConnection(object):  
  @classmethod
  def configure_options(cls, options=None):
    if options is None:
      options = {'user':DEFAULT_USER, 'password':DEFAULT_PASS, 'host': DEFAULT_HOST, 'core_db': DEFAULT_CORE_DB}
    else: 
      if not options.has_key('user'):
        options['user'] = DEFAULT_USER
      if not options.has_key('password'):
        options['password'] = DEFAULT_PASS
      if not options.has_key('host'):
        options['host'] = DEFAULT_HOST
      if not options.has_key('core_db'):
        options['core_db'] = DEFAULT_CORE_DB

    return options
  
  def __init__(self, options=None):
    options = MysqlConnection.configure_options(options)
    self.user = options['user']
    self.password = options['password']
    self.host = options['host']
    self.core_db = options['core_db']
    self.connection_string = self.get_connection_string(options)
    self.connection = self.create_connection(options)
  
  def get_connection_string(self, options=None):
    return "mysql://%s:%s@%s/%s" % (options['user'], options['password'], options['host'], options['core_db'])
  
  def create_connection(self, options=None):
    connection_string = self.get_connection_string(options)   
    connection_core = sqlobject.connectionForURI(connection_string)
    sqlobject.sqlhub.processConnection = connection_core
    return connection_core
          
  def write_query(self, query):
    self.connection.query(query)
  
  def read_query(self, query):
    return self.connection.queryAll(query)